import { Selector } from '@ngxs/store';
import { ShopState, ShopStateModel } from './shop.state';
import * as _ from 'lodash';

export class ShopSelector {
  @Selector([ShopState])
  static form({form}: ShopStateModel) {
    return form?.model;
  }

  @Selector([ShopState])
  static formFlag({formFlag}: ShopStateModel) {
    return formFlag;
  }

  @Selector([ShopState])
  static list({list}: ShopStateModel) {
    return list;
  }

  @Selector([ShopState])
  static cart({cart}: ShopStateModel) {
    return cart;
  }

  @Selector([ShopState])
  static cartList({cart, list}: ShopStateModel) {
    if (!cart || Object.keys(cart).length === 0) return [];
    return Object.keys(cart).filter(s => !!s).map(s => {
      let r = _.find(list, a => a.id === s);
      return {key: s, count: cart[s], name: r.name, price: r.price};
    });
  }

  @Selector([ShopState])
  static cartCount({cart}: ShopStateModel) {
    let count = 0;
    Object.keys(cart).forEach(s => {
      count += cart[s];
    });
    return count;
  }

  @Selector([ShopSelector.cartCount])
  static showCount(count: number) {
    return !count ? false : count > 0;
  }

  @Selector([ShopState])
  static cartTotalPrice({cart, list}: ShopStateModel) {
    let totalPrice = 0;
    Object.keys(cart).forEach(k => {
      let r = _.find(list, s => s.id === k);
      if (!!r) totalPrice += r.price * cart[k];
    });
    return totalPrice;
  }
}
